<template>
  <div class="review-statistics">
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="课程">
          <el-select
            v-model="filterForm.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教练">
          <el-select
            v-model="filterForm.coachId"
            placeholder="请选择教练"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="coach in coachOptions"
              :key="coach.id"
              :label="coach.name"
              :value="coach.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadStatistics" :loading="loading">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 总体统计 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="item-icon" style="background-color: #409eff;">
              <el-icon><Comment /></el-icon>
            </div>
            <div class="item-content">
              <div class="item-value">{{ statistics.totalReviews }}</div>
              <div class="item-label">总评价数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="item-icon" style="background-color: #67c23a;">
              <el-icon><Star /></el-icon>
            </div>
            <div class="item-content">
              <div class="item-value">{{ statistics.avgRating.toFixed(1) }}</div>
              <div class="item-label">平均评分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="item-icon" style="background-color: #e6a23c;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="item-content">
              <div class="item-value">{{ getGoodReviewRate() }}%</div>
              <div class="item-label">好评率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="item-icon" style="background-color: #f56c6c;">
              <el-icon><HotWater /></el-icon>
            </div>
            <div class="item-content">
              <div class="item-value">{{ statistics.featuredReviews.length }}</div>
              <div class="item-label">精选评价</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 评分分布 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>评分分布</span>
            </div>
          </template>
          <div ref="ratingChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>趋势分析</span>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程/教练排行 -->
    <el-row :gutter="20" v-if="statistics.courseStats || statistics.coachStats">
      <el-col :span="12" v-if="statistics.courseStats">
        <el-card class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>课程评价排行</span>
            </div>
          </template>
          <el-table :data="statistics.courseStats" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip />
            <el-table-column prop="totalReviews" label="评价数" width="100" />
            <el-table-column prop="avgRating" label="平均分" width="100">
              <template #default="scope">
                {{ scope.row.avgRating.toFixed(1) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12" v-if="statistics.coachStats">
        <el-card class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>教练评价排行</span>
            </div>
          </template>
          <el-table :data="statistics.coachStats" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="coachName" label="教练姓名" show-overflow-tooltip />
            <el-table-column prop="totalReviews" label="评价数" width="100" />
            <el-table-column prop="avgRating" label="平均分" width="100">
              <template #default="scope">
                {{ scope.row.avgRating.toFixed(1) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 精选评价 -->
    <el-card class="featured-reviews-card" v-if="statistics.featuredReviews.length > 0">
      <template #header>
        <div class="card-header">
          <span>精选评价</span>
        </div>
      </template>
      <div class="featured-reviews">
        <div
          v-for="review in statistics.featuredReviews"
          :key="review.id"
          class="review-item"
        >
          <div class="review-header">
            <div class="user-info">
              <el-avatar :src="review.user.avatar" size="small" />
              <span class="user-name">{{ review.user.name }}</span>
            </div>
            <el-rate
              v-model="review.rating"
              disabled
              size="small"
            />
          </div>
          <div class="review-content">{{ review.content }}</div>
          <div class="review-footer">
            <span class="review-time">{{ formatTime(review.createdAt) }}</span>
            <el-tag type="success" v-if="review.isFeatured">精选</el-tag>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type { ReviewStatisticsResponse, CourseReview } from '@/types/api/review'
import { reviewManagementApi } from '@/api/modules/review'

// 图表引用
const ratingChartRef = ref<HTMLDivElement | null>(null)
const trendChartRef = ref<HTMLDivElement | null>(null)
let ratingChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// loading 状态
const loading = ref(false)

// 过滤表单
const dateRange = ref<[string, string]>(['', ''])
const filterForm = reactive({
  courseId: undefined as number | undefined,
  coachId: undefined as number | undefined
})

// 模拟课程和教练选项
const courseOptions = ref([
  { id: 1, name: '瑜伽基础班' },
  { id: 2, name: '动感单车' },
  { id: 3, name: '普拉提' }
])

const coachOptions = ref([
  { id: 1, name: '张教练' },
  { id: 2, name: '李教练' },
  { id: 3, name: '王教练' }
])

// 统计数据
const statistics = ref<ReviewStatisticsResponse>({
  period: '',
  totalReviews: 0,
  avgRating: 0,
  ratingDistribution: {
    '1': 0,
    '2': 0,
    '3': 0,
    '4': 0,
    '5': 0
  },
  dailyTrend: [],
  featuredReviews: []
})

// 获取好评率
const getGoodReviewRate = () => {
  const goodReviews = statistics.value.ratingDistribution['4'] + statistics.value.ratingDistribution['5']
  return statistics.value.totalReviews > 0
    ? ((goodReviews / statistics.value.totalReviews) * 100).toFixed(1)
    : '0.0'
}

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleDateString()
}

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    const params: any = {}

    // 处理日期范围
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }

    // 处理课程和教练筛选
    if (filterForm.courseId) {
      params.courseId = filterForm.courseId
    }
    if (filterForm.coachId) {
      params.coachId = filterForm.coachId
    }

    const response = await reviewManagementApi.getReviewStatistics(params)
    statistics.value = response.data.data

    // 渲染图表
    await nextTick()
    renderCharts()
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 重置过滤器
const resetFilter = () => {
  dateRange.value = ['', '']
  filterForm.courseId = undefined
  filterForm.coachId = undefined
  loadStatistics()
}

// 渲染评分分布图表
const renderRatingChart = () => {
  if (!ratingChartRef.value) return

  if (!ratingChart) {
    ratingChart = echarts.init(ratingChartRef.value)
  }

  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '评分分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: statistics.value.ratingDistribution['5'], name: '5星' },
          { value: statistics.value.ratingDistribution['4'], name: '4星' },
          { value: statistics.value.ratingDistribution['3'], name: '3星' },
          { value: statistics.value.ratingDistribution['2'], name: '2星' },
          { value: statistics.value.ratingDistribution['1'], name: '1星' }
        ]
      }
    ]
  }

  ratingChart.setOption(option)
}

// 渲染趋势图表
const renderTrendChart = () => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dates = statistics.value.dailyTrend.map(item => item.date)
  const counts = statistics.value.dailyTrend.map(item => item.count)
  const ratings = statistics.value.dailyTrend.map(item => item.avgRating)

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['评价数量', '平均评分']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '评价数量'
      },
      {
        type: 'value',
        name: '平均评分',
        min: 0,
        max: 5,
        interval: 1
      }
    ],
    series: [
      {
        name: '评价数量',
        type: 'bar',
        data: counts
      },
      {
        name: '平均评分',
        type: 'line',
        yAxisIndex: 1,
        data: ratings,
        smooth: true
      }
    ]
  }

  trendChart.setOption(option)
}

// 渲染所有图表
const renderCharts = () => {
  renderRatingChart()
  renderTrendChart()
}

// 监听窗口大小变化，重新渲染图表
window.addEventListener('resize', () => {
  if (ratingChart) ratingChart.resize()
  if (trendChart) trendChart.resize()
})

// 生命周期
onMounted(() => {
  loadStatistics()
})
</script>

<style scoped>
.review-statistics {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.summary-row {
  margin-bottom: 20px;
}

.summary-card {
  height: 120px;
}

.summary-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.item-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.item-icon .el-icon {
  font-size: 28px;
  color: white;
}

.item-content {
  flex: 1;
}

.item-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.item-label {
  font-size: 14px;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

.ranking-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.featured-reviews {
  max-height: 400px;
  overflow-y: auto;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-name {
  margin-left: 10px;
  font-weight: bold;
}

.review-content {
  margin-bottom: 10px;
  line-height: 1.5;
}

.review-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}
</style>
